package com.hymall.service.wx;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hymall.bean.*;
import com.hymall.bean.bo.CommentBO;
import com.hymall.bean.bo.WXOrderBO;

import com.hymall.bean.common.BasePageInfo;
import com.hymall.bean.common.CommonData;
import com.hymall.bean.vo.WXOrderDetailVO;
import com.hymall.bean.vo.WXOrderListVO;
import com.hymall.mapper.*;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: haiyuny
 * @Date: 2022/7/19 10:04
 * @Description:
 */
@Service
public class WOrderServiceImpl implements WOrderService {
    @Autowired
    MarketOrderMapper orderMapper;
    @Autowired
    MarketOrderGoodsMapper orderGoodsMapper;
    @Autowired
    MarketCommentMapper commentMapper;

    /*
     * @author 李海云
     * @description 逻辑支付
     * @date 2022/7/18 9:06
     * @param orderId
     * @return
     */
    @Override
    public void prepay(String orderId) {
        MarketOrder marketOrder = orderMapper.selectByPrimaryKey(Integer.parseInt(orderId));
        marketOrder.setOrderStatus(((short) 201));
        marketOrder.setPayTime(new Date());
        marketOrder.setPayId(orderId);
        orderMapper.updateByPrimaryKey(marketOrder);
    }

    /*
     * @author 李海云
     * @description 订单删除
     * @date 2022/7/18 9:06
     * @param orderId
     * @return
     */
    @Override
    @Transactional
    public void deleteOrder(WXOrderBO orderId) {
        MarketOrderExample moe = new MarketOrderExample();

        moe.createCriteria().andIdEqualTo(Integer.parseInt(orderId.getOrderId()));
        List<MarketOrder> marketOrders = orderMapper.selectByExample(moe);
        MarketOrder marketOrder = marketOrders.get(0);
        marketOrder.setDeleted(true);
        marketOrder.setUpdateTime(new Date());
        orderMapper.updateByExample(marketOrder, moe);

        MarketOrderGoodsExample moge = new MarketOrderGoodsExample();
        moge.createCriteria().andOrderIdEqualTo(Integer.parseInt(orderId.getOrderId()));
        List<MarketOrderGoods> marketOrderGoods = orderGoodsMapper.selectByExample(moge);
        for (MarketOrderGoods marketOrderGood : marketOrderGoods) {
            MarketOrderGoods marketOrderGoods1 = new MarketOrderGoods();
            BeanUtils.copyProperties(marketOrderGood, marketOrderGoods1);
            marketOrderGoods1.setDeleted(true);
            moge.clear();
            moge.createCriteria().andIdEqualTo(marketOrder.getId());
            orderGoodsMapper.updateByExample(marketOrderGoods1, moge);
        }

    }

    /*
     * @author 李海云
     * @description 订单显示
     * @date 2022/7/18 9:06
     * @param
     * @return CommonData 商品展示订单信息
     */
    @Override
    public CommonData queryOrderLists(BasePageInfo info, Short showType) {
        PageHelper.startPage(info.getPage(), info.getLimit());


        MarketOrderExample moe = new MarketOrderExample();

        moe.setOrderByClause("add_time desc");
        MarketOrderExample.Criteria criteria = moe.createCriteria();
        MarketUser subject = (MarketUser) SecurityUtils.getSubject().getPrincipal();
        Integer userId = subject.getId();
        System.out.println(userId);
        criteria.andDeletedEqualTo(false).andUserIdEqualTo(userId);

        switch (showType) {
            case 0:
                List<Short> shorts = new LinkedList<>();
                shorts.add(((short) 101));
                shorts.add(((short) 201));
                shorts.add(((short) 301));
                shorts.add(((short) 401));
                shorts.add(((short) 202));
                criteria.andOrderStatusIn(shorts);
                break;
            case 1:
                criteria.andOrderStatusEqualTo(((short) 101));
                break;
            case 2:
                criteria.andOrderStatusEqualTo(((short) 201));
                break;
            case 3:
                criteria.andOrderStatusEqualTo(((short) 301));
                break;
            case 4:
                criteria.andOrderStatusEqualTo(((short) 401));
        }
        List<MarketOrder> marketOrders = orderMapper.selectByExample(moe);
        List<WXOrderListVO> list = new LinkedList<>();
        for (MarketOrder marketOrder : marketOrders) {
            WXOrderListVO wx = new WXOrderListVO();
            BeanUtils.copyProperties(marketOrder, wx, "orderStatusText", "isGroupin", "goodsList", "handleOption");
            wx.setActualPrice(marketOrder.getActualPrice().doubleValue());
            BigDecimal bigDecimal = new BigDecimal(0);
            if (marketOrder.getGrouponPrice().compareTo(bigDecimal) == 0) {
                wx.setIsGroupin(false);
            }
            Short orderStatus = marketOrder.getOrderStatus();
            if (orderStatus == 101) {
                wx.setOrderStatusText("待付款");
            }
            if (orderStatus == 201) {
                wx.setOrderStatusText("待发货");
            }
            if (orderStatus == 301) {
                wx.setOrderStatusText("待收货");
            }
            if (orderStatus == 401) {
                wx.setOrderStatusText("待评价");
            }
            if (orderStatus == 202) {
                wx.setOrderStatusText("订单取消中，待退款");
            }

            WXOrderListVO.HandleOptionEntity handleOptionEntity = wx.new HandleOptionEntity();
            handleOptionEntity.setPay((marketOrder.getOrderStatus() == 101));
            handleOptionEntity.setDelete(marketOrder.getDeleted());
            handleOptionEntity.setRefund((marketOrder.getRefundAmount() == null));
            handleOptionEntity.setComment((marketOrder.getComments() != 0));
            handleOptionEntity.setConfirm(!(marketOrder.getOrderStatus() == 301));
            handleOptionEntity.setAftersale((marketOrder.getAftersaleStatus() == 0));
            handleOptionEntity.setCancel((marketOrder.getOrderStatus() == 101));
            handleOptionEntity.setRebuy((marketOrder.getOrderStatus() == 401 || marketOrder.getOrderStatus() == 402));
            wx.setHandleOption(handleOptionEntity);


            MarketOrderGoodsExample moge = new MarketOrderGoodsExample();
            moge.createCriteria().andOrderIdEqualTo(marketOrder.getId());
            List<MarketOrderGoods> marketOrderGoods = orderGoodsMapper.selectByExample(moge);
            List<WXOrderListVO.GoodsListEntity> goods = new LinkedList<>();
            for (MarketOrderGoods marketOrderGood : marketOrderGoods) {
                WXOrderListVO.GoodsListEntity goodsListEntity = wx.new GoodsListEntity();
                goodsListEntity.setNumber(marketOrderGood.getNumber());
                goodsListEntity.setPicUrl(marketOrderGood.getPicUrl());
                goodsListEntity.setPrice(marketOrderGood.getPrice().doubleValue());
                goodsListEntity.setId(marketOrderGood.getGoodsId());
                goodsListEntity.setGoodsName(marketOrderGood.getGoodsName());
                goodsListEntity.setSpecifications(marketOrderGood.getSpecificationsList());
                goods.add(goodsListEntity);
            }
            wx.setGoodsList(goods);
            list.add(wx);
        }

        PageInfo<WXOrderListVO> pageInfo = new PageInfo<>(list);
        return CommonData.data(pageInfo);
    }

    /*
     * @author 李海云
     * @description 订单详情
     * @date 2022/7/18 9:06
     * @param orderId
     * @return
     */
    @Override
    public WXOrderDetailVO getOrderDetail(String orderId) {
        WXOrderDetailVO wx = new WXOrderDetailVO();
        WXOrderDetailVO.OrderInfoEntity orderInfoEntity = wx.new OrderInfoEntity();
        wx.setOrderInfo(orderInfoEntity);
        MarketOrder marketOrder = orderMapper.selectByPrimaryKey(Integer.parseInt(orderId));
        System.out.println(orderId);

        if ((marketOrder.getShipChannel() != null) && (!"".equals(marketOrder.getShipChannel()))) {
            String s = orderMapper.selectChannelByCode(marketOrder.getShipChannel());
            orderInfoEntity.setExpName(s);
            System.out.println(s);
        }
        BeanUtils.copyProperties(marketOrder, orderInfoEntity);
        orderInfoEntity.setActualPrice(marketOrder.getActualPrice().doubleValue());

        orderInfoEntity.setGoodsPrice(marketOrder.getActualPrice().doubleValue());
        orderInfoEntity.setExpNo(marketOrder.getShipSn());
        Short orderStatus = marketOrder.getOrderStatus();
        if (orderStatus == 101) {
            orderInfoEntity.setOrderStatusText("待付款");
        }
        if (orderStatus == 201) {
            orderInfoEntity.setOrderStatusText("待发货");
        }
        if (orderStatus == 301) {
            orderInfoEntity.setOrderStatusText("待收货");
        }
        if (orderStatus == 401) {
            orderInfoEntity.setOrderStatusText("待评价");
        }


        WXOrderDetailVO.OrderInfoEntity.HandleOptionEntity handleOptionEntity = orderInfoEntity.new HandleOptionEntity();
        handleOptionEntity.setPay((marketOrder.getOrderStatus() == 101));
        handleOptionEntity.setDelete(marketOrder.getDeleted());
        handleOptionEntity.setRefund((marketOrder.getRefundAmount() == null));
        handleOptionEntity.setComment((marketOrder.getComments() != 0) && (orderStatus == 401));
        handleOptionEntity.setConfirm((marketOrder.getOrderStatus() == 301));
        handleOptionEntity.setAftersale((marketOrder.getAftersaleStatus() == 0) && (marketOrder.getOrderStatus() == 401 || marketOrder.getOrderStatus() == 402));

        handleOptionEntity.setCancel((marketOrder.getOrderStatus() == 101));
        handleOptionEntity.setRebuy((marketOrder.getOrderStatus() == 401 || marketOrder.getOrderStatus() == 402));

        orderInfoEntity.setHandleOption(handleOptionEntity);
        List<WXOrderDetailVO.OrderGoodsEntity> goods = new LinkedList<>();

        MarketOrderGoodsExample moge = new MarketOrderGoodsExample();
        moge.createCriteria().andOrderIdEqualTo(marketOrder.getId());
        List<MarketOrderGoods> marketOrderGoods = orderGoodsMapper.selectByExample(moge);
        for (MarketOrderGoods marketOrderGood : marketOrderGoods) {
            WXOrderDetailVO.OrderGoodsEntity orderGoodsEntity = wx.new OrderGoodsEntity();
            BeanUtils.copyProperties(marketOrderGood, orderGoodsEntity, "specifications");
            orderGoodsEntity.setNumber(marketOrderGood.getNumber());
            orderGoodsEntity.setSpecifications(marketOrderGood.getSpecificationsList());
            goods.add(orderGoodsEntity);
        }
        wx.setOrderGoods(goods);
        return wx;
    }

    /*
     * @author 李海云
     * @description 确认收货
     * @date 2022/7/18 9:06
     * @param orderId
     * @return
     */
    @Override
    public void confirm(String orderId) {
        MarketOrder marketOrder = orderMapper.selectByPrimaryKey(Integer.parseInt(orderId));
        marketOrder.setOrderStatus(((short) 401));
        marketOrder.setUpdateTime(new Date());
        orderMapper.updateByPrimaryKey(marketOrder);
    }

    /*
     * @author 李海云
     * @description 获取订单商品
     * @date 2022/7/18 9:06
     * @param orderId
     * @return
     */
    @Override
    public MarketOrderGoods goods(String orderId, String goodsId) {

        MarketOrderGoodsExample moge = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = moge.createCriteria().andOrderIdEqualTo(Integer.parseInt(orderId)).andGoodsIdEqualTo(Integer.parseInt(goodsId));
        List<MarketOrderGoods> marketOrderGoods = orderGoodsMapper.selectByExample(moge);
        MarketOrderGoods orderGoods = marketOrderGoods.get(0);
        return orderGoods;
    }

    /*
     * @author 李海云
     * @description 评论
     * @date 2022/7/18 9:06
     * @param orderId
     * @return
     */
    @Override
    @Transactional
    public void comment(CommentBO commentBO) {
        MarketOrderGoods orderGoods = orderGoodsMapper.selectByPrimaryKey(commentBO.getOrderGoodsId());
        MarketOrder marketOrder = orderMapper.selectByPrimaryKey(orderGoods.getOrderId());

        Short comments = marketOrder.getComments();
        marketOrder.setComments(--comments);
        if (comments == 0) {
            marketOrder.setOrderStatus(((short) 402));
        }
        orderMapper.updateByPrimaryKey(marketOrder);

        MarketComment marketComment = new MarketComment();
        BeanUtils.copyProperties(commentBO, marketComment);
        marketComment.setValueId(0);
        marketComment.setType(((byte) 0));
        marketComment.setUserId(marketOrder.getUserId());
        marketComment.setAddTime(new Date());
        commentMapper.insert(marketComment);
        orderGoods.setComment(marketComment.getId());
        orderGoodsMapper.updateByPrimaryKey(orderGoods);
        orderGoods.setComment(marketComment.getId());

    }

    /*
     * @author 李海云
     * @description 申请退款
     * @date 2022/7/18 9:06
     * @param orderId
     * @return
     */
    @Override
    public void refund(WXOrderBO orderId) {

        orderMapper.orderRefund(Integer.parseInt(orderId.getOrderId()));
    }

    /*
     * @author 李海云
     * @description 取消订单
     * @date 2022/7/18 9:06
     * @param orderId
     * @return
     */
    @Override
    @Transactional
    public void cancel(WXOrderBO orderId) {
        MarketOrder marketOrder = orderMapper.selectByPrimaryKey(Integer.parseInt(orderId.getOrderId()));
        marketOrder.setOrderStatus(((short) 102));
        orderMapper.updateByPrimaryKey(marketOrder);
    }


    /**
     * @author 牟治宇
     * @description 订单提交
     * @date 2022/7/21 21:04
     * @param
     * @return
     */
    @Autowired
    MarketAddressMapper marketAddressMapper;
    @Autowired
    MarketCartMapper marketCartMapper;

    @Transactional
    @Override
    public Integer orderSubmit(Integer addressId, Integer cartId, Integer couponId, Integer grouponLinkId, Integer grouponRulesId, String message) {


        MarketAddress marketAddress = marketAddressMapper.selectByPrimaryKey(addressId);
        Integer userId = marketAddress.getUserId();

        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.createCriteria().andUserIdEqualTo(userId).andCheckedEqualTo(true).andDeletedEqualTo(false);

        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);


        Integer orderId = createOrder(addressId, marketCarts, couponId, grouponLinkId, grouponRulesId, message);

        createOrderGoods(orderId, marketCarts);

        return orderId;
    }


    @Autowired
    MarketOrderGoodsMapper marketOrderGoodsMapper;

    private void createOrderGoods(Integer orderId, List<MarketCart> marketCarts) {
        if (marketCarts == null) {
            return;
        }


        for (MarketCart marketCart : marketCarts) {

            MarketOrderGoods orderGoods = new MarketOrderGoods();
            orderGoods.setOrderId(orderId);
            orderGoods.setGoodsId(marketCart.getGoodsId());
            orderGoods.setGoodsName(marketCart.getGoodsName());
            orderGoods.setGoodsSn(marketCart.getGoodsSn());
            orderGoods.setProductId(marketCart.getProductId());
            orderGoods.setNumber(marketCart.getNumber());
            orderGoods.setPrice(marketCart.getPrice());
            orderGoods.setComment(0);
            orderGoods.setAddTime(new Date(System.currentTimeMillis()));
            orderGoods.setUpdateTime(new Date(System.currentTimeMillis()));
            orderGoods.setDeleted(false);
            System.out.println(marketCart.getSpecificationsList());
            orderGoods.setSpecifications(marketCart.getSpecificationsList());
            orderGoods.setPicUrl(marketCart.getPicUrl());
            marketOrderGoodsMapper.insertSelective(orderGoods);
            marketCartMapper.deleteById(marketCart.getId());
        }

    }


    /**
     * @author 牟治宇
     * @description 创建订单的相关表项
     * @date 2022/7/21 20:05
     * @param
     * @return
     */
    @Autowired
    MarketCouponMapper marketCouponMapper;
    @Autowired
    MarketOrderMapper marketOrderMapper;

    private Integer createOrder(Integer addressId,
                                List<MarketCart> marketCarts, Integer couponId,
                                Integer grouponLinkId, Integer grouponRulesId, String message) {
        MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(couponId);


        MarketAddress marketAddress = marketAddressMapper.selectByPrimaryKey(addressId);

        MarketOrder order = new MarketOrder();
        order.setUserId(marketAddress.getUserId());
        order.setConsignee(marketAddress.getName());
        order.setOrderSn(createOrderSn());
        int status = 201;
        order.setOrderStatus((short) status);
        order.setMobile(marketAddress.getTel());
        order.setMessage(message);

        String province = marketAddress.getProvince();
        String city = marketAddress.getCity();
        String county = marketAddress.getCounty();
        order.setAddress(province + city + county);
        order.setPayTime(new Date(System.currentTimeMillis()));

        //商品价格
        BigDecimal orderGoodsPrice = getOrderGoodsPrice(marketAddress.getUserId(), marketCarts);
        order.setGoodsPrice(orderGoodsPrice);

        //货运价格
        BigDecimal fieightPrice = getOrderFreightPrice(orderGoodsPrice);
        order.setFreightPrice(fieightPrice);

        //积分价格
        BigDecimal integralPrice = new BigDecimal("0");
        order.setIntegralPrice(integralPrice);

        //团购价格
        BigDecimal grouponPrice = new BigDecimal("0");
        order.setGrouponPrice(grouponPrice);

        //订单费用


        //优惠券价格
        BigDecimal counponPrice = null;
        if (counponPrice != null) {
            counponPrice = marketCoupon.getDiscount();
            int code = marketCouponMapper.setCouponUsed(marketAddress.getUserId(), couponId);
        } else {
            counponPrice = new BigDecimal("0");
        }
        order.setCouponPrice(counponPrice);


        //真实价格
        BigDecimal actualPrice = orderGoodsPrice.add(fieightPrice).subtract(counponPrice).add(integralPrice);
        order.setActualPrice(actualPrice);

        order.setOrderPrice(actualPrice);

        short s = 0;
        order.setComments(s);
        order.setAddTime(new Date(System.currentTimeMillis()));
        order.setUpdateTime(new Date(System.currentTimeMillis()));
        order.setDeleted(false);

        marketOrderMapper.insertSelective(order);

        return order.getId();
    }

    private BigDecimal getOrderFreightPrice(BigDecimal orderGoodsPrice) {

        BigDecimal a = new BigDecimal("300");

        if (a.compareTo(orderGoodsPrice) == -1) {
            return new BigDecimal("18");
        }
        return new BigDecimal("0");

    }

    private BigDecimal getOrderGoodsPrice(Integer userId, List<MarketCart> marketCarts) {

        BigDecimal orderPrice = new BigDecimal("0.0");
        for (MarketCart marketCart : marketCarts) {
            BigDecimal price = new BigDecimal(marketCart.getPrice().toString());
            BigDecimal num = new BigDecimal(marketCart.getNumber().toString());
            orderPrice = orderPrice.add(price.multiply(num));

        }
        return orderPrice;
    }


    // @Autowired
    // MarketAddressMapper marketRegionMapper;
    //
    // private String getDetailAddress(MarketAddress marketAddress) {
    //
    //     marketRegionMapper.selectByPrimaryKey(marketAddress.)
    //
    //
    // }


    /**
     * @param []
     * @return java.lang.String
     * @author 牟治宇
     * @description 生成订单号的方法
     * @date 2022/7/21 20:04
     */
    private String createOrderSn() {
        long l = System.currentTimeMillis();
        String s = RandomStringUtils.randomNumeric(6);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String orderSn = sdf.format(new Date(Long.parseLong(String.valueOf(l)))) + s;
        return orderSn;
    }
}
